import contentPools from "../dbs/main.db";
import { http } from 'system';

/**
 * 获取内容池分页列表
 * @param {number} [sourceId] - 抓取源ID筛选（可选）
 * @param {string} [contentType] - 内容类型筛选（可选）
 * @param {number} [page=1] - 页码（默认1）
 * @param {number} [pageSize=10] - 每页数量（默认10）
 * @returns {Object} 标准响应格式 {code:number, message:string, data: { list:[{id:number, source_id:number, content_id:number, template_id:number, title:string, content:string, content_type:string, status:number, reject_reason:string, analysis_data:string, create_at:string, modify_time:string, content_title:string}], total:number, page:number, pageSize:number }}
 */
async function getContentPoolList(sourceId, contentType, page = 1, pageSize = 10) {
    try {
        const queryParams = {
            "total@": "[]/total",
            "[]": {
                page,
                count: pageSize,
                query: 2,
                "content_pools": {
                    "@order": "create_time-",
                },
                "crawl_site_content": {
                    "id@": "content_pools/content_id",
                    "@column": "id,title"
                }
            }
        };

        // 添加筛选条件
        if (sourceId) {
            queryParams["[]"]["content_pools"]["source_id"] = sourceId;
        }
        if (contentType) {
            queryParams["[]"]["content_pools"]["content_type"] = contentType;
        }

        const result = await contentPools.queryAsync(queryParams);

        // 处理结果，合并内容标题
        const list = (result["[]"] || []).map(item => {
            const contentPool = item.content_pools || {};
            const content = item.crawl_site_content || {};

            return {
                ...contentPool,
                content_title: content.title || ""
            };
        });

        return {
            code: 200,
            message: '',
            data: {
                list,
                total: result.total || 0,
                page,
                pageSize
            }
        };
    } catch (error) {
        console.error('获取内容池列表失败:', error);
        return {
            code: 500,
            message: '获取内容池列表失败',
            data: error.message
        };
    }
}

/**
 * 获取内容池详情
 * @param {number} id - 内容池ID
 * @returns {Object} 标准响应格式 {code:number, message:string, data: {id:number, source_id:number, content_id:number, template_id:number, title:string, content:string, content_type:string, status:number, reject_reason:string, analysis_data:string, create_at:string, modify_time:string, content_title:string}}
 */
async function getContentPoolDetail(id) {
    try {
        const result = await contentPools.queryAsync({
            "content_pools": {
                id
            },
            "crawl_site_content": {
                "id@": "content_pools/content_id",
                "@column": "id,title"
            }
        });

        if (result.content_pools?.id) {
            const contentPool = result.content_pools;
            const content = result.crawl_site_content || {};

            return {
                code: 200,
                message: '',
                data: {
                    ...contentPool,
                    content_title: content.title || ""
                }
            };
        } else {
            return {
                code: 404,
                message: '内容池项不存在',
                data: null
            };
        }
    } catch (error) {
        console.error('获取内容池详情失败:', error);
        return {
            code: 500,
            message: '获取内容池详情失败',
            data: error.message
        };
    }
}

/**
 * 添加内容池项
 * @param {number} sourceId - 抓取源ID
 * @param {number} contentId - 内容ID
 * @param {number} templateId - 模板ID
 * @param {string} contentType - 内容类型
 * @param {string} title - 标题
 * @param {string} content - 内容
 * @param {Object} analysisData - 分析数据
 * @returns {Object} 标准响应格式 {code:number, message:string, data:{id:number}}
 */
async function addContentPool(sourceId, contentId, templateId, contentType, title, content, analysisData) {
    try {
        const newContentPool = {
            source_id: sourceId,
            content_id: contentId,
            template_id: templateId,
            content_type: contentType,
            title: title,
            content: content,
            analysis_data: JSON.stringify(analysisData),
            status: 0 // 默认待审核状态
        };

        const id = await contentPools.addAsync({
            "content_pools": newContentPool
        });

        return {
            code: 200,
            message: '添加内容池项成功',
            data: { id }
        };
    } catch (error) {
        console.error('添加内容池项失败:', error);
        return {
            code: 500,
            message: '添加内容池项失败',
            data: error.message
        };
    }
}

/**
 * 更新内容池项
 * @param {number} id - 内容池ID
 * @param {string} contentType - 内容类型
 * @param {string} title - 标题
 * @param {string} content - 内容
 * @param {Object} analysisData - 分析数据
 * @returns {Object} 标准响应格式 {code:number, message:string, data:null}
 */
async function updateContentPool(id, contentType, title, content, analysisData) {
    try {
        const updateData = {
            id,
            content_type: contentType,
            title: title,
            content: content,
            analysis_data: JSON.stringify(analysisData),
            modify_time: new Date().toISOString().replace("T", " ").substr(0, 19)
        };

        await contentPools.modifyAsync({
            "content_pools": updateData
        });

        return {
            code: 200,
            message: '更新内容池项成功',
            data: null
        };
    } catch (error) {
        console.error('更新内容池项失败:', error);
        return {
            code: 500,
            message: '更新内容池项失败',
            data: error.message
        };
    }
}

/**
 * 删除内容池项
 * @param {number} id - 内容池ID
 * @returns {Object} 标准响应格式 {code:number, message:string, data:null}
 */
async function deleteContentPool(id) {
    try {
        await contentPools.removeAsync({
            "content_pools": {
                id
            }
        });

        return {
            code: 200,
            message: '删除内容池项成功',
            data: null
        };
    } catch (error) {
        console.error('删除内容池项失败:', error);
        return {
            code: 500,
            message: '删除内容池项失败',
            data: error.message
        };
    }
}

/**
 * 生成多模态内容
 * @param {number} templateId - 模板ID
 * @param {Object} analysisData - 分析数据
 * @param {string} contentType - 内容类型
 * @param {string} title - 标题
 * @returns {Object} 标准响应格式 {code:number, message:string, data:{contentId:number, contentType:string, title:string, content:string}}
 */
async function generateMultiModalContent(templateId, analysisData, contentType, title) {
    try {
        // 这里应该调用AI服务生成多模态内容
        // 由于iToolX框架限制，这里模拟生成过程
        const generatedContent = `AI生成的${contentType}类型内容，基于模板${templateId}和分析数据`;
        const generatedData = {
            templateId,
            analysisData,
            contentType,
            generatedContent,
            generatedAt: new Date().toISOString().replace("T", " ").substr(0, 19)
        };

        // 创建内容池项
        const newContentPool = {
            template_id: templateId,
            content_type: contentType,
            title: title,
            content: generatedContent,
            analysis_data: JSON.stringify(generatedData),
            status: 0 // 待审核状态
        };

        const contentId = await contentPools.addAsync({
            "content_pools": newContentPool
        });

        return {
            code: 200,
            message: '生成多模态内容成功',
            data: {
                contentId,
                contentType,
                title,
                content: generatedContent
            }
        };
    } catch (error) {
        console.error('生成多模态内容失败:', error);
        return {
            code: 500,
            message: '生成多模态内容失败',
            data: error.message
        };
    }
}

/**
 * 审核通过内容
 * @param {number} id - 内容池ID
 * @returns {Object} 标准响应格式 {code:number, message:string, data:null}
 */
async function approveContent(id) {
    try {
        const updateData = {
            id,
            status: 1, // 已通过
            modify_time: new Date().toISOString().replace("T", " ").substr(0, 19)
        };

        await contentPools.modifyAsync({
            "content_pools": updateData
        });

        return {
            code: 200,
            message: '审核通过成功',
            data: null
        };
    } catch (error) {
        console.error('审核通过失败:', error);
        return {
            code: 500,
            message: '审核通过失败',
            data: error.message
        };
    }
}

/**
 * 审核拒绝内容
 * @param {number} id - 内容池ID
 * @param {string} reason - 拒绝原因
 * @returns {Object} 标准响应格式 {code:number, message:string, data:null}
 */
async function rejectContent(id, reason) {
    try {
        const updateData = {
            id,
            status: 2, // 已拒绝
            reject_reason: reason,
            modify_time: new Date().toISOString().replace("T", " ").substr(0, 19)
        };

        await contentPools.modifyAsync({
            "content_pools": updateData
        });

        return {
            code: 200,
            message: '审核拒绝成功',
            data: null
        };
    } catch (error) {
        console.error('审核拒绝失败:', error);
        return {
            code: 500,
            message: '审核拒绝失败',
            data: error.message
        };
    }
}

// 导出所有方法
export {
    getContentPoolList,
    getContentPoolDetail,
    addContentPool,
    updateContentPool,
    deleteContentPool,
    generateMultiModalContent,
    approveContent,
    rejectContent
};